package com.elock.service.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elock.base.core.Filter;
import com.elock.base.core.Pageable;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.dao.SaleOrgBaseDao;
import com.elock.entity.MemberSaleOrg;
import com.elock.entity.SaleOrg;
import com.elock.service.MemberSaleOrgBaseService;
import com.elock.service.MemberService;
import com.elock.service.SaleOrgBaseService;

/**
 * Service - 组织
 *
 */
@Service("saleOrgBaseServiceImpl")
public class SaleOrgBaseServiceImpl extends BaseServiceImpl<SaleOrg> implements SaleOrgBaseService {

	@Resource(name = "saleOrgBaseDao")
	private SaleOrgBaseDao saleOrgBaseDao;
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
	@Resource(name = "memberSaleOrgBaseServiceImpl")
	private MemberSaleOrgBaseService memberSaleOrgBaseService;

	@Override
	public SaleOrg getCurrentSaleOrg() {
		List<Filter> fis = new ArrayList<Filter>();
		fis.add(Filter.eq("member", memberService.getCurrent()));
		MemberSaleOrg memberSaleOrg = memberSaleOrgBaseService.find(fis);
		return memberSaleOrg.getSaleOrg();
	}

	@Override
	@Transactional(readOnly = true)
	public List<SaleOrg> findTree(String name, Boolean isEnabled) {
		return saleOrgBaseDao.findChildren(name, isEnabled, null, 0);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SaleOrg> findChildren(String name, Boolean isEnabled, SaleOrg saleOrg) {
		return saleOrgBaseDao.findChildren(name, isEnabled, saleOrg, 0);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findList(String saleOrgName, String sn, Boolean isEnabled, Pageable pageable) {
		return saleOrgBaseDao.findList(saleOrgName, sn, isEnabled, pageable);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findChildren(Long parentId) {
		return saleOrgBaseDao.findChildren(parentId);
	}

	@Override
	@Transactional(readOnly = true)
	public SaleOrg findByStoreMember(Long storeMemberId) {
		return saleOrgBaseDao.findByStoreMember(storeMemberId);
	}

	@Override
	@Transactional
	public void deleteSaleOrg(SaleOrg saleOrg) {
		SaleOrg parent = saleOrg.getParent();

		delete(saleOrg);

		if (parent != null && (parent.getChildren() == null || parent.getChildren().size() < 2)) {
			parent.setIsLeaf(true);
			update(parent);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public String saleOrgAuth() {
		return saleOrgBaseDao.saleOrgAuth();
	}

	@Override
	@Transactional(readOnly = true)
	public int sameSaleOrgSn(String sn, Long id) {
		return saleOrgBaseDao.sameSaleOrgSn(sn, id);
	}
}
